package org.mitoma.logger.client;

import org.mitoma.logger.shared.AuthInfo;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootLayoutPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class CycleLogger implements EntryPoint {

  private static final RegExp REGISTER_TOKEN = RegExp.compile("^r:(.*)$");

  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {
    GlobalRepository.getService().isLoggedIn(new AsyncCallback<AuthInfo>() {

      @Override
      public void onFailure(Throwable caught) {
        System.out.println("failure");
        String token = History.getToken();
        if (REGISTER_TOKEN.test(token)) {
          showRegisterdTop(token);
        }
        showMainPanel();
      }

      @Override
      public void onSuccess(AuthInfo info) {
        showMainPanel();
        GlobalRepository.setAuthInfo(info);
        GlobalRepository.moveToTop();
      }
    });
  }

  private void showMainPanel() {
    RootLayoutPanel.get().add(GlobalRepository.getMainPanel());
  }

  private void showRegisterdTop(String token) {
    MatchResult result = REGISTER_TOKEN.exec(token);
    String userId = result.getGroup(1);

    GlobalRepository.getService().register(userId,
        new AsyncCallback<AuthInfo>() {

          @Override
          public void onSuccess(AuthInfo info) {
            GlobalRepository.setAuthInfo(info);
            GlobalRepository.moveToRegisterComplete();
          }

          @Override
          public void onFailure(Throwable caught) {
            showMainPanel();
          }
        });

  }
}
